package com.zt.yzmlogin.controller;
import com.zt.yzmlogin.entity.User;
import com.zt.yzmlogin.service.YzmService;
import com.zt.yzmlogin.util.Result;
import com.zt.yzmlogin.util.Yzmtil;
import com.zt.yzmlogin.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/yzm")
@CrossOrigin
public class sjhyzController {
    @Autowired
    private YzmService yzmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private JwtUtil jwtUtil;

    @RequestMapping("/get")
    public Result get(String phone){
   if (StringUtils.isEmpty(phone)) {
       return new Result(false, "手机号不能为空");
   }

   String coders = redisTemplate.opsForValue().get(phone);
   System.err.println("手机号：" + phone + "，验证码：" + coders);

   if (!ObjectUtils.isEmpty(coders)){
       return new Result(true, "验证码已发送，请勿重复获取", coders);
   }

   coders = String.valueOf(Yzmtil.generateValidateCode(6));
   //发送短信服务
   boolean send = true; // 测试环境直接返回true，跳过实际短信发送
   if (send){
       //存入redis当中
       redisTemplate.opsForValue().set(phone,coders,5, TimeUnit.MINUTES);
       return new Result(true, "验证码发送成功", coders);
   }
        return new Result(false, "验证码发送失败");
    }

    @RequestMapping("/login")
    public Result login(String phone, String code) {
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            return new Result(false, "手机号或验证码不能为空");
        }

        // 从Redis获取验证码
        String savedCode = redisTemplate.opsForValue().get(phone);
        if (StringUtils.isEmpty(savedCode)) {
            return new Result(false, "验证码已过期，请重新获取");
        }

        // 验证码校验
        if (!code.equals(savedCode)) {
            return new Result(false, "验证码错误");
        }

 // 验证成功后删除Redis中的验证码
 redisTemplate.delete(phone);

 // 查询或创建用户
 User user = yzmService.findOrCreateUser(phone);
 // 生成token
 String token = jwtUtil.generateToken(phone);
    // 返回token和用户信息
    Map<String, Object> data = new HashMap<>();
 data.put("userId", user.getUserId());  // 添加用户ID
         data.put("phone", phone);
        data.put("token", token);

        return new Result( true, "登录成功", data);
        }
        }